package com.pine.common.threadpool.core;

import com.pine.common.threadpool.RejectedPolicyFactory;
import com.pine.common.threadpool.ThreadFactory;
import com.pine.common.threadpool.ThreadPoolConfig;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池工厂
 *
 * @author pine manage
 * @since 2024-08-28
 */
@Slf4j
public class ThreadPoolExecutorFactory {

    public static ThreadPoolExecutor createThreadPoolExecutor(String businessCode, String businessKey) {
        try {
            // 通过业务编码和key获取线程池配置
            ThreadPoolConfig threadPoolConfig = ThreadPoolConfigFactory.getThreadPoolConfig(businessCode, businessKey);

            // 创建线程池
            return new ThreadPoolExecutor(
                    threadPoolConfig.getCorePoolSize(),
                    threadPoolConfig.getMaximumPoolSize(),
                    threadPoolConfig.getKeepAliveTime(),
                    threadPoolConfig.getKeepAliveTimeUnit(),
                    new LinkedBlockingQueue<>(threadPoolConfig.getBlockingQueueCapacity()),
                    new ThreadFactory(businessKey),
                    RejectedPolicyFactory.getRejectedPolicy(threadPoolConfig.getRejectedPolicyCode())
            );
        } catch (Exception e) {
            log.error("ThreadPoolExecutorFactory.createThreadPoolExecutor({}, {}) error", businessCode, businessKey, e);
            throw new RuntimeException("ThreadPoolExecutorFactory.createThreadPoolExecutor error.");
        }
    }
}
